<template>
  <div>
    <PageTools>
      <template #left>
        <div class="tips">
          <i class="el-icon-info" />
          <span>共{{ total }}条数据</span>
        </div>
      </template>
      <template #right>
        <el-button
          type="danger"
          size="small"
          @click="handleDownload"
        >普通excel导出</el-button>
        <el-button type="info" size="small">复杂标头ecxel导出</el-button>
        <el-button type="success" size="small" @click="$router.push('/import')">excel导入</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog"
        >新增员工</el-button>
      </template>
    </PageTools>
    <!-- 表格区域 -->
    <el-card style="margin-top: 10px">
      <el-table border :data="list">
        <el-table-column label="序号" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像" prop="staffPhoto" align="center">
          <template #default="scope">
            <img :src="scope.row.staffPhoto" alt="" class="headImg">
          </template>
        </el-table-column>
        <el-table-column label="手机号" prop="mobile" />
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment">
          <template #default="scope">
            {{ hireMap[+scope.row.formOfEmployment] || "未知" }}
          </template>
        </el-table-column>
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" prop="timeOfEntry">
          <template #default="scope">
            {{ formatDate(scope.row.timeOfEntry) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="toDetail(scope.row.id)"
            >查看</el-button>
            <!-- <el-button type="text" size="small" @click="$router.push(`/employeeDetail/${scope.row.id}`)">查看</el-button> -->
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="showAssignRole(scope.row.id)">角色</el-button>
            <el-button
              type="text"
              size="small"
              @click="delFn(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="center" align="middle" style="height: 60px">
        <el-pagination
          :current-page="params.page"
          :page-size="params.size"
          :total="total"
          layout="total,prev,pager,next"
          hide-on-single-page
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>
    <!-- 子组件,对话框 -->
    <AddDialog
      :dialog-visible="dialogVisible"
      @close="close"
      @add="fetchEmployeeList"
    />
    <!-- 给员工分配角色弹窗 -->
    <el-dialog
      title="分配角色"
      :visible="assignRoleVisible"
      @close="assignRoleClose"
      @open="assignRoleOpen"
    >
      <!-- 角色多选框 -->
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
          {{ item.name }}
        </el-checkbox>
      </el-checkbox-group>
      <!-- 按钮区域 -->
      <template #footer>
        <el-button size="small" @click="assignRoleClose">取消</el-button>
        <el-button type="primary" size="small" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee, getRoleList, assignRoles, getUserDetailById } from '@/api'
import dayjs from 'dayjs'
import AddDialog from './components/AddDialog.vue'
export default {
  components: {
    PageTools,
    AddDialog
  },
  data() {
    return {
      // 员工列表数据
      list: [],
      params: {
        page: 1, // 当前页
        size: 10 // 每页条数
      },
      // 数据条数
      total: 0,
      // 定义聘用形式的枚举
      // 前端对数字映射的渲染
      // 通常是后端告诉前端有几个数字
      // 不同的数字对应不同的文字
      // 前端需要定义一个对象存储数字和汉字的映射关系
      hireMap: {
        1: '正式',
        2: '非正式'
      },
      // 控制对话框显示与隐藏
      dialogVisible: false,
      // 控制分配角色弹窗的显示与隐藏
      assignRoleVisible: false,
      // 角色列表
      roleList: [],
      // 选中的角色 id 组成的数组
      roleIds: [],
      // 员工id
      employeeId: ''
    }
  },
  created() {
    this.fetchEmployeeList()
  },
  methods: {
    // 打开弹窗
    async assignRoleOpen() {
      const { data } = await getRoleList({
        page: 1,
        pagesize: 100
      })
      this.roleList = data.rows
      // this.roleId = id
      const res = await getUserDetailById(this.employeeId)
      this.roleIds = res.data.roleIds
    },
    // 格式化时间
    formatDate(value) {
      return dayjs(value).format('YYYY-MM-DD')
    },
    // 分页改变后触发
    handleCurrentChange(newPage) {
      this.params.page = newPage
      this.fetchEmployeeList()
    },
    // 获取员工列表
    async fetchEmployeeList() {
      const {
        data: { rows, total }
      } = await getEmployeeList(this.params)
      this.list = rows
      this.total = total
    },
    // 展示新增对话框
    showDialog() {
      this.dialogVisible = true
    },
    // 关闭对话框
    close() {
      this.dialogVisible = false
    },
    // 删除员工
    delFn(val) {
      console.log(val)
      this.$confirm('确定删除该员工吗?', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await delEmployee(val.id)
          this.$message.success('删除员工成功！')
          // 做边界处理, 删除最后一页最后一条数据时，页数减 1
          if (this.list.length === 1 && this.params.page > 1) {
            this.params.page--
          }
          this.fetchEmployeeList()
        })
        .catch(() => {
          this.$message.info('取消删除！')
        })
    },
    // 导出功能
    handleDownload() {
      // 动态引入 @/vendor/Export2Excel 包
      import('@/vendor/Export2Excel').then(async(excel) => {
        // 调接口，获取员工列表的接口
        const res = await getEmployeeList(this.params)
        // 表头
        const headerArr = [
          '姓名',
          '手机号',
          '入职日期',
          '工号',
          '聘用形式',
          '部门'
        ]
        // 中英对照关系
        const headerRelation = {
          姓名: 'username',
          手机号: 'mobile',
          入职日期: 'timeOfEntry',
          工号: 'workNumber',
          聘用形式: 'formOfEmployment',
          部门: 'departmentName'
        }
        const towArr = this.getExportData(
          res.data.rows,
          headerArr,
          headerRelation
        )
        console.log(towArr)
        // excel：是 @/vendor/Export2Excel 包中的 excel 导出模块
        // export_json_to_excel：将 json 数据转换为 excel
        excel.export_json_to_excel({
          // 表头 header 必填，是一个数组
          header: headerArr,
          // 表格 body 具体数据，是一个二维数组
          data: towArr,
          filename: '你好世界', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 导出数据处理方法
    getExportData(rows, headerArr, headerRelation) {
      const twoArr = []
      rows.forEach((item) => {
        const oneArr = []
        headerArr.forEach((key) => {
          const enKey = headerRelation[key]
          if (enKey === 'formOfEmployment') {
            oneArr.push(this.hireMap[+item[enKey]] || '未知')
          } else {
            oneArr.push(item[enKey])
          }
        })
        twoArr.push(oneArr)
      })
      return twoArr
    },
    // 员工详情跳转
    toDetail(id) {
      // 跳转到员工详情页，并传递参数
      this.$router.push({
        path: '/employeeDetail',
        query: {
          id
        }
      })
    },
    // 显示分配角色弹窗
    async showAssignRole(id) {
      this.assignRoleVisible = true
      this.employeeId = id
    },
    // 分配角色弹窗关闭，执行的回调
    assignRoleClose() {
      this.assignRoleVisible = false
      // 清空选中的角色
      this.roleIds = []
    },
    // 提交分配角色
    async submit() {
      await assignRoles({
        id: this.employeeId,
        roleIds: this.roleIds
      })
      // 提示用户
      this.$message.success('分配角色成功')
      // 关闭弹窗
      this.assignRoleClose()
    }
  }
}
</script>

<style lang="scss" scoped>
.headImg {
  display: inline-block;
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>>

